package my.graduation.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: RavenLyn
 * @Date: 2024-11-29
 */

/**
 * 医疗卡号生成
 */
public class MedicalCardGenerator {
    // 数据库中的patient表medicalCard字段使用UNIQUE关键字配合使用，保证存储的卡号唯一。
    private static long lastTimestamp = -1L;
    private static long sequence = 0L;
    private static final Lock lock = new ReentrantLock();

    public static String generateCardId() {
        lock.lock();
        try {
            long timestamp = System.currentTimeMillis();
            if (timestamp < lastTimestamp) {
                // 处理时钟回拨问题
                throw new RuntimeException("Clock moved backwards. Refusing to generate id");
            }
            if (lastTimestamp == timestamp) {
                sequence = (sequence + 1) % 1000;
                if (sequence == 0) {
                    // 等待下一个毫秒
                    timestamp = waitNextMillis(lastTimestamp);
                }
            } else {
                sequence = 0;
                lastTimestamp = timestamp;
            }
            // 取timestamp的后三位和sequence组成10位诊疗卡号
            // 将timestamp转换为字符串，取后三位
            String timestampStr = String.valueOf(timestamp);
            int timestampMod = timestampStr.length() > 3 ? Integer.parseInt(timestampStr.substring(timestampStr.length() - 3)) : 0;
            // 生成后七位随机数
            int randomSequence = ThreadLocalRandom.current().nextInt(1000000, 10000000);
            // 拼接成10位诊疗卡号
            return String.format("%03d%07d", timestampMod, randomSequence);
        } finally {
            lock.unlock();
        }
    }

    private static long waitNextMillis(long lastTimestamp) {
        while (true) {
            long now = System.currentTimeMillis();
            if (now > lastTimestamp) {
                return now;
            }
        }
    }
}
